const {spawn} = require('child_process');

let localGitStorePath;

class GitShell {
  constructor(gitPath, GitStorePath) {
    this.gitPath = gitPath;
    localGitStorePath = GitStorePath;
  }

  /**
   * @desc 从远端clone指定的仓库文件到指定的位置
   * @param gitUrl {String} 远端的git厂库地址
   * @param gitLocalPath {String} 本地的存储地址
   */
  async clone(gitUrl) {
    if (!this.gitPath) {
      return console.error('未指定git命令地址');
    }
    console.log('开始clone', gitUrl);
    const res = await spanFun(this.gitPath, ['clone', gitUrl, localGitStorePath]);
    if (!res) return;
    console.log(res);
    return true;
  }

  async add() {
    const res = await spanFun(this.gitPath, ['add', '.']);
    if (!res) return;
    console.log(res);
    return true;
  }

  async commit() {
    const msg = 'commit is ' + new Date().getTime();
    const res = await spanFun(this.gitPath, ['commit', '-m', `"${msg}"`]);
    if (!res) return;
    console.log(res);
    return true;
  }

  async pull() {
    const res = await spanFun(this.gitPath, ['pull']);
    if (!res) return;
    console.log(res);
    return true;
  }

  async push() {
    const res = await spanFun(this.gitPath, ['push']);
    if (!res) return;
    console.log(res);
    return true;
  }

  async reportData() {
    const addStatus = await this.add();
    if (!addStatus) return 0;
    const commitStatus = await this.commit();
    if (!commitStatus) return 1;
    const pullStatus = await this.pull();
    if (!pullStatus) return 2;
    const pushStatus = await this.push();
    if (!pushStatus) return 3;
    return 4;

  }
}

function spanFun(shellName, shellOptions = []) {
  return new Promise((s, f) => {
    let msg = [];
    console.log('开始执行', shellName, shellOptions.join(' '));
    let spawnObj = spawn(shellName, shellOptions, {
      cwd: localGitStorePath
    });
    spawnObj.stdout.on('data', function (data) {
      msg.push(data.toString());
      console.log('data => ', data.toString());
    });
    spawnObj.stderr.on('err', (err) => {
      console.log(`${shellOptions[0]} error`);
      console.log(err);
      s(null);
    });
    spawnObj.on('close', (code) => {
      console.log(`${shellOptions[0]} exit code is ${code}`);
      s({code, msg});
    });
  });
}

module.exports = GitShell;
